package club.ljwang.wechat;

import club.ljwang.constant.MessageConstant;
import club.ljwang.constant.RedisMessageConstant;
import club.ljwang.entity.Result;
import club.ljwang.pojo.Member;
import club.ljwang.service.MemberService;
import club.ljwang.utils.JedisUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @Auther: wangl
 * @Date: 2020/3/5 16:35
 * @Description:
 */

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private JedisUtil jedisUtil;

    @Reference
    private MemberService memberService;

    @RequestMapping("check")
    public Result check(@RequestBody Map map, HttpServletRequest request) {

        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        String redisCode = jedisUtil.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (redisCode == null || !validateCode.equals(redisCode)) {

            return new Result(false, MessageConstant.VALIDATECODE_ERROR);

        }

        Member member = memberService.findTelephone(telephone);

        if (member == null) {

            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member = memberService.add(member);

        }

        //request.getSession().setAttribute("member",member);

        String LoginToken = UUID.randomUUID().toString();
        jedisUtil.setex(LoginToken,60*60*24*15, JSON.toJSONString(member));


        return new Result(true, MessageConstant.LOGIN_SUCCESS,LoginToken);


    }

}
